/**
 * @program: LeetCode
 * @description: LeetCode :
 * @author: WXY
 * @create: 2023-01-02 10:06
 * @Version 1.0
 **/
public class offer_sixteen2_Codec {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public class Codec {


        StringBuilder sb = new StringBuilder();
        String[] strings;
        int index = 0;

        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            dfs(root);
            return sb.toString();
        }

        private void dfs(TreeNode root) {
            if (root == null) {
                sb.append("*" + " ");
            } else {
                sb.append(String.valueOf(root.val) + " ");
                dfs(root.left);
                dfs(root.right);
            }
        }

        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            strings = data.split(" ");
            return build();
        }

        private TreeNode build() {
            String string = strings[index];
            if (string.equals("*")) {
                return null;
            }
            TreeNode node = new TreeNode(Integer.valueOf(string));
            index++;
            node.left = build();
            index++;
            node.right = build();
            return node;
        }

    }
}
